import 'dart:math';

import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import '../../resources/kq_theme_colors.dart';
import '../../resources/l10n/kq_intl.dart';
import 'package:kq_flutter_core_widget/utils/ex/string_ex.dart';
import 'package:kq_flutter_core_widget/utils/text_filed_utils.dart';
import 'package:kq_flutter_core_widget/utils/text_input_format_utils.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../../config/kq_global.dart';
import '../../resources/images.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import '../textFiled/kq_textfiled.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 原因选择+数量
///
/// 左边删除图标 + 标题 + 选择原因 + 下拉图标 + 数量减按钮  + 数量输入框 + 数量加按钮
///
/// 推荐直接使用[KqAddNumberItemView]
///
/// 如果单独使用，需和[KqFormQtyEntity]使用
///
/// 标题：title
/// 选择提示：hint
/// 选择的显示值使用：valueForShow
/// 选择的提交值使用:valueForSubmit
/// 数字值使用：qty
///
/// @author 周卓
///
class KqNumberItemView extends StatefulWidget {
  /// 子控件数据
  final KqFormQtyEntity entity;

  /// 选择控件点击回调
  final Function(KqFormQtyEntity entity)? onTap;

  /// 数量组件删除按钮点击回调
  final Function(KqFormQtyEntity entity)? onRemove;

  const KqNumberItemView(
      {Key? key, required this.entity, this.onTap, this.onRemove})
      : super(key: key);

  @override
  KqNumberItemViewState createState() => KqNumberItemViewState();
}

class KqNumberItemViewState extends State<KqNumberItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;
    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  /// 点击减号
  void _onDec() {
    var qty = widget.entity.qty;
    if (qty > widget.entity.minQty) {
      _onValueChanged((widget.entity.qty - 1).toString());
      widget.entity.onNumberQtyChanged?.call(widget.entity);
    }
  }

  /// 点击加号
  void _onPlus() {
    var qty = widget.entity.qty;
    if (qty < (widget.entity.max ?? 999999999)) {
      _onValueChanged((widget.entity.qty + 1).toString());
      widget.entity.onNumberQtyChanged?.call(widget.entity);
    }
  }

  /// 输入框数值变化
  void _onValueChanged(String text) {
    setState(() {
      widget.entity.isEmpty = text.isEmpty;
      widget.entity.qty = text.isEmpty ? widget.entity.minQty : int.parse(text);
      if (widget.entity.qty < widget.entity.minQty) {
        widget.entity.qty = widget.entity.minQty;
      }
    });
  }

  // 减号能不能点
  bool _decAble() {
    return widget.entity.qty > widget.entity.minQty;
  }

  // 加号能不能点
  bool _addAble() {
    return widget.entity.qty < (widget.entity.max ?? 999999999);
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    // 背景颜色
    var bgColor = widget.entity.backgroundColor ??
        (widget.entity.isEditable()
            ? KqThemeColors.bgF5
            : KqThemeColors.bgWhite);
    return Container(
      color: bgColor,
      child: Column(
        children: [
          Padding(
            padding: EdgeInsets.only(
                left: widget.entity.isEditable() ? 0 : 16.r, right: 16.r),
            child: Row(
              children: [
                /// 左边减号
                if (widget.entity.isEditable())
                  InkWell(
                    onTap: () {
                      if (widget.entity.removable) {
                        if (widget.entity.onRemove != null) {
                          widget.entity.onRemove!(widget.entity);
                        }
                        if (widget.onRemove != null) {
                          widget.onRemove!(widget.entity);
                        }
                      }
                    },
                    child: Container(
                        alignment: Alignment.centerRight,
                        height: 44.r,
                        padding: EdgeInsets.only(left: 16.r, right: 12.r),
                        child: Image.asset(
                          widget.entity.removable
                              ? Images.commonIcRemoveFillEnabled
                              : Images.commonIcRemoveFillDisabled,
                          width: 18.r,
                          height: 18.r,
                          fit: BoxFit.fill,
                          package: KqGlobal.packageName,
                        )),
                  ),
                Expanded(
                    child: Row(
                  children: [
                    /// 选择项
                    Expanded(
                        child: KqInkWell(
                      verticalPadding: widget.entity.paddingVertical ??
                          KqThemeManager.instance
                              .getConfig()
                              .formConfig
                              .paddingVertical ??
                          15.r,
                      onTap: widget.entity.isEditable() &&
                              widget.entity.onTapEnable
                          ? () {
                              TextFiledUtil.clearFocus(context);
                              if (widget.entity.onTap != null) {
                                widget.entity.onTap!(widget.entity);
                              }
                              if (widget.onTap != null) {
                                widget.onTap!(widget.entity);
                              }
                            }
                          : null,
                      child: Row(
                        children: [
                          /// 选择的文字
                          Expanded(
                              child: Text(
                            widget.entity.valueForShow ??
                                (widget.entity.isEditable()
                                    ? ((widget.entity.hint ??
                                        KqIntl.currentResource.pleaseChoose))
                                    : ''),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                              fontSize: KqThemeManager.instance
                                      .getConfig()
                                      .formConfig
                                      .contentFontSize ??
                                  16.sp,
                              color: widget.entity.valueForShow != null
                                  ? KqThemeColors.text26
                                  : KqThemeColors.textBF,
                            ),
                          )),

                          /// 下拉箭头
                          if (widget.entity.isEditable() &&
                              widget.entity.onTapEnable)
                            Image.asset(
                              Images.commonIcZhankai16Grey,
                              width: 16.r,
                              height: 16.r,
                              fit: BoxFit.fill,
                              package: KqGlobal.packageName,
                            )
                        ],
                      ),
                    )),
                    SizedBox(
                      width: 24.r,
                      height: 1,
                    ),

                    if (widget.entity.unit.isNullOrEmpty)
                      SizedBox(
                        width: 30.r,
                      ),

                    /// 数量减
                    if (widget.entity.isEditable())
                      InkWell(
                        onTap: () => _onDec(),
                        child: Image.asset(
                          _decAble()
                              ? Images.commonIcReduceNormal
                              : Images.commonIcReduceDisabled,
                          width: 32.r,
                          height: 26.r,
                          fit: BoxFit.fill,
                          package: KqGlobal.packageName,
                        ),
                      ),
                    if (widget.entity.isEditable())
                      SizedBox(
                        width: 4.r,
                        height: 1,
                      ),

                    /// 数量输入框
                    if (widget.entity.isEditable())
                      SizedBox(
                        width: 46.r,
                        child: KqTextFiled(
                          inputType: TextInputType.number,
                          multiline: false,
                          maxLines: 1,
                          enableClearButton: false,
                          textAlign: TextAlign.center,
                          newValue: widget.entity.isEmpty
                              ? null
                              : widget.entity.qty.toString(),
                          fontSize: KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .contentFontSize ??
                              14.sp,
                          onMonitor: (str) {
                            widget.entity.onNumberQtyChanged
                                ?.call(widget.entity);
                          },
                          defValue: widget.entity.qty.toString(),
                          placeHolder: widget.entity.minQty.toString(),
                          inputFormatters:
                              widget.entity.inputFormattersTextRight ??
                                  TextInputFormatUtils.integer(),
                          onChanged: (value) => _onValueChanged(value),
                        ),
                      ),
                    if (widget.entity.isEditable())
                      SizedBox(
                        width: 4.r,
                        height: 1,
                      ),

                    /// 数量加
                    if (widget.entity.isEditable())
                      InkWell(
                        onTap: () => _onPlus(),
                        child: Image.asset(
                          _addAble()
                              ? Images.commonIcIncreaseNormal
                              : Images.commonIcIncreaseDisabled,
                          width: 32.r,
                          height: 26.r,
                          fit: BoxFit.fill,
                          package: KqGlobal.packageName,
                        ),
                      ),

                    if (!widget.entity.isEditable())
                      Text(
                        widget.entity.qty.toString(),
                        style: TextStyle(
                            fontSize: KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .contentFontSize ??
                                14.sp,
                            color: KqThemeColors.text59),
                      ),

                    /// 单位
                    Visibility(
                        visible: widget.entity.unit.isNotNullOrEmpty,
                        child: Container(
                          alignment: Alignment.centerRight,
                          width: 40.r,
                          padding: EdgeInsets.only(
                              left: widget.entity.isEditable() ? 8.r : 12.r),
                          child: Text(
                            widget.entity.unit.fixSoftWrap() ?? '',
                            maxLines: 1,
                            textAlign: TextAlign.end,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(
                                fontSize: KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .unitFontSize ??
                                    14.sp,
                                color: widget.entity.unitColor ??
                                    KqThemeColors.text59),
                          ),
                        ))
                  ],
                ))
              ],
            ),
          ),
          KqDivider(
            leftMargin: !widget.entity.dividerHorMarginEnable
                ? 0
                : widget.entity.paddingHorizontal ??
                    KqThemeManager.instance
                        .getConfig()
                        .formConfig
                        .paddingHorizontal ??
                    16.r,
            rightMargin: !widget.entity.dividerHorMarginEnable
                ? 0
                : widget.entity.paddingHorizontal ??
                    KqThemeManager.instance
                        .getConfig()
                        .formConfig
                        .paddingHorizontal ??
                    16.r,
          ),
        ],
      ),
    );
  }
}
